const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(morgan('dev'));

// 在路由处理前添加延迟中间件
app.use((req, res, next) => {
  setTimeout(next, 300); // 300ms延迟
});

// 随机错误中间件
app.use((req, res, next) => {
  // 10%概率返回错误
  if (Math.random() < 0.1) {
    return res.status(500).json({
      code: 500,
      message: '模拟服务器错误'
    });
  }
  next();
});

// 加载模拟数据
const loadMockData = (filename) => {
  const filePath = path.join(__dirname, 'data', `${filename}.json`);
  try {
    const data = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.error(`Error loading mock data from ${filePath}:`, error);
    return {};
  }
};

// 路由设置
app.get('/', (req, res) => {
  res.json({
    message: '音乐应用模拟API服务',
    endpoints: [
      { path: '/api/songs', description: '获取歌曲列表' },
      { path: '/api/songs/:id', description: '获取单个歌曲详情' },
      { path: '/api/artists', description: '获取艺术家列表' },
      { path: '/api/artists/:id', description: '获取艺术家详情' },
      { path: '/api/playlists', description: '获取歌单列表' },
      { path: '/api/playlists/:id', description: '获取歌单详情' },
      { path: '/api/rankings', description: '获取排行榜数据' },
      { path: '/api/search', description: '搜索接口' }
    ]
  });
});

// 歌曲列表接口
app.get('/api/songs', (req, res) => {
  const songs = loadMockData('songs');
  res.json(songs);
});

// 单个歌曲详情接口
app.get('/api/songs/:id', (req, res) => {
  const songs = loadMockData('songs');
  const song = songs.data.find(s => s.id === parseInt(req.params.id));
  
  if (song) {
    res.json({ code: 0, data: song });
  } else {
    res.status(404).json({ code: 404, message: '歌曲不存在' });
  }
});

// 艺术家列表接口
app.get('/api/artists', (req, res) => {
  const artists = loadMockData('artists');
  res.json(artists);
});

// 艺术家详情接口
app.get('/api/artists/:id', (req, res) => {
  const artists = loadMockData('artists');
  const artist = artists.data.find(a => a.id === parseInt(req.params.id));
  
  if (artist) {
    res.json({ code: 0, data: artist });
  } else {
    res.status(404).json({ code: 404, message: '艺术家不存在' });
  }
});

// 歌单列表接口
app.get('/api/playlists', (req, res) => {
  const playlists = loadMockData('playlists');
  res.json(playlists);
});

// 歌单详情接口
app.get('/api/playlists/:id', (req, res) => {
  const playlists = loadMockData('playlists');
  const playlist = playlists.data.find(p => p.id === parseInt(req.params.id));
  
  if (playlist) {
    res.json({ code: 0, data: playlist });
  } else {
    res.status(404).json({ code: 404, message: '歌单不存在' });
  }
});

// 排行榜数据接口
app.get('/api/rankings', (req, res) => {
  const rankings = loadMockData('rankings');
  res.json(rankings);
});

// 搜索接口
app.get('/api/search', (req, res) => {
  const { keyword, type = 'song' } = req.query;
  
  if (!keyword) {
    return res.status(400).json({ code: 400, message: '搜索关键词不能为空' });
  }
  
  let results;
  
  switch (type) {
    case 'song':
      const songs = loadMockData('songs').data;
      results = songs.filter(song => 
        song.name.toLowerCase().includes(keyword.toLowerCase()) ||
        song.artist.toLowerCase().includes(keyword.toLowerCase())
      );
      break;
    case 'artist':
      const artists = loadMockData('artists').data;
      results = artists.filter(artist => 
        artist.name.toLowerCase().includes(keyword.toLowerCase())
      );
      break;
    case 'playlist':
      const playlists = loadMockData('playlists').data;
      results = playlists.filter(playlist => 
        playlist.name.toLowerCase().includes(keyword.toLowerCase())
      );
      break;
    default:
      return res.status(400).json({ code: 400, message: '不支持的搜索类型' });
  }
  
  res.json({ code: 0, data: results });
});

// 模拟登录接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  
  if (username === 'admin' && password === 'password') {
    res.json({
      code: 0,
      data: {
        token: 'mock-jwt-token',
        user: {
          id: 1,
          username: 'admin',
          nickname: '管理员'
        }
      }
    });
  } else {
    res.status(401).json({
      code: 401,
      message: '用户名或密码错误'
    });
  }
});

// 需要身份验证的接口中间件
const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization;
  
  if (token === 'Bearer mock-jwt-token') {
    next();
  } else {
    res.status(401).json({
      code: 401,
      message: '未授权或token已过期'
    });
  }
};

// 使用身份验证中间件
app.get('/api/user/profile', authMiddleware, (req, res) => {
  res.json({
    code: 0,
    data: {
      id: 1,
      username: 'admin',
      nickname: '管理员',
      avatar: 'https://example.com/avatar.jpg'
    }
  });
});

// 获取社交动态列表
app.get('/api/moments', (req, res) => {
  const moments = loadMockData('moments');
  res.json(moments);
});

// 获取单个动态详情
app.get('/api/moments/:id', (req, res) => {
  const moments = loadMockData('moments');
  const moment = moments.data.find(m => m.id === parseInt(req.params.id));
  
  if (moment) {
    res.json({ code: 0, data: moment });
  } else {
    res.status(404).json({ code: 404, message: '动态不存在' });
  }
});

// 发布动态
app.post('/api/moments', authMiddleware, (req, res) => {
  const { content, images = [], musicId } = req.body;
  
  if (!content && images.length === 0) {
    return res.status(400).json({ code: 400, message: '动态内容不能为空' });
  }
  
  // 模拟成功率80%
  if (Math.random() < 0.8) {
    res.json({
      code: 0,
      data: {
        id: Date.now(),
        content,
        images,
        musicId,
        user: {
          id: 1,
          username: 'admin',
          nickname: '管理员',
          avatar: 'https://example.com/avatar.jpg'
        },
        likes: 0,
        comments: 0,
        shares: 0,
        createTime: new Date().toISOString()
      },
      message: '发布成功'
    });
  } else {
    res.status(500).json({ code: 500, message: '发布失败，请重试' });
  }
});

// 点赞动态
app.post('/api/moments/:id/like', authMiddleware, (req, res) => {
  const momentId = parseInt(req.params.id);
  const moments = loadMockData('moments');
  const moment = moments.data.find(m => m.id === momentId);
  
  if (!moment) {
    return res.status(404).json({ code: 404, message: '动态不存在' });
  }
  
  res.json({
    code: 0,
    data: {
      liked: true,
      likes: moment.likes + 1
    },
    message: '点赞成功'
  });
});

// 取消点赞
app.delete('/api/moments/:id/like', authMiddleware, (req, res) => {
  const momentId = parseInt(req.params.id);
  const moments = loadMockData('moments');
  const moment = moments.data.find(m => m.id === momentId);
  
  if (!moment) {
    return res.status(404).json({ code: 404, message: '动态不存在' });
  }
  
  res.json({
    code: 0,
    data: {
      liked: false,
      likes: Math.max(0, moment.likes - 1)
    },
    message: '取消点赞成功'
  });
});

// 评论动态
app.post('/api/moments/:id/comments', authMiddleware, (req, res) => {
  const { content } = req.body;
  const momentId = parseInt(req.params.id);
  
  if (!content) {
    return res.status(400).json({ code: 400, message: '评论内容不能为空' });
  }
  
  const moments = loadMockData('moments');
  const moment = moments.data.find(m => m.id === momentId);
  
  if (!moment) {
    return res.status(404).json({ code: 404, message: '动态不存在' });
  }
  
  res.json({
    code: 0,
    data: {
      id: Date.now(),
      content,
      momentId,
      user: {
        id: 1,
        username: 'admin',
        nickname: '管理员',
        avatar: 'https://example.com/avatar.jpg'
      },
      createTime: new Date().toISOString()
    },
    message: '评论成功'
  });
});

// 获取动态评论列表
app.get('/api/moments/:id/comments', (req, res) => {
  const momentId = parseInt(req.params.id);
  const comments = loadMockData('comments');
  
  // 筛选指定动态的评论
  const filteredComments = comments.data.filter(c => c.momentId === momentId);
  
  res.json({
    code: 0,
    data: filteredComments
  });
});

// 自定义错误处理
app.use((req, res) => {
  res.status(404).json({ code: 404, message: '接口不存在' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`模拟API服务器运行在 http://localhost:${PORT}`);
  
  // 确保数据目录存在
  const dataDir = path.join(__dirname, 'data');
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir);
    console.log('已创建数据目录');
    
    // 创建示例数据文件
    createExampleDataFiles(dataDir);
  }
});

// 创建示例数据文件
function createExampleDataFiles(dataDir) {
  // 歌曲数据
  const songs = {
    code: 0,
    data: [
      {
        id: 1,
        name: '时光流逝',
        artist: 'Gfriend',
        album: '回忆',
        duration: '03:45',
        cover: 'https://example.com/covers/time.jpg',
        url: 'https://example.com/songs/time.mp3',
        type: 'SQ',
        isExclusive: true
      },
      {
        id: 2,
        name: '玻璃珠',
        artist: 'Gfriend',
        album: '第三张专辑',
        duration: '04:12',
        cover: 'https://example.com/covers/glass.jpg',
        url: 'https://example.com/songs/glass.mp3',
        type: 'SQ',
        isExclusive: false
      },
      {
        id: 3,
        name: '夏天的风',
        artist: '木子蘭',
        album: '夏日记忆',
        duration: '03:28',
        cover: 'https://example.com/covers/summer.jpg',
        url: 'https://example.com/songs/summer.mp3',
        type: 'SQ',
        isExclusive: false
      },
      {
        id: 4,
        name: '我的快乐',
        artist: '银河',
        album: '星空下的约定',
        duration: '04:05',
        cover: 'https://example.com/covers/happiness.jpg',
        url: 'https://example.com/songs/happiness.mp3',
        type: 'SQ',
        isExclusive: false
      },
      {
        id: 5,
        name: 'Tell Me',
        artist: '木子蘭',
        album: '心声',
        duration: '03:55',
        cover: 'https://example.com/covers/tellme.jpg',
        url: 'https://example.com/songs/tellme.mp3',
        type: 'SQ',
        isExclusive: true
      }
    ]
  };

  // 艺术家数据
  const artists = {
    code: 0,
    data: [
      {
        id: 1,
        name: 'Gfriend',
        avatar: 'https://example.com/artists/gfriend.jpg',
        fans: 5473000,
        songs: 110,
        albums: 35,
        description: '韩国女子组合'
      },
      {
        id: 2,
        name: '木子蘭',
        avatar: 'https://example.com/artists/mulan.jpg',
        fans: 3250000,
        songs: 78,
        albums: 12,
        description: '华语流行歌手'
      },
      {
        id: 3,
        name: '银河',
        avatar: 'https://example.com/artists/galaxy.jpg',
        fans: 1890000,
        songs: 45,
        albums: 8,
        description: '独立音乐人'
      }
    ]
  };

  // 歌单数据
  const playlists = {
    code: 0,
    data: [
      {
        id: 1,
        name: '最懂你的华语歌曲推荐',
        cover: 'https://example.com/playlists/chinese.jpg',
        creator: '音乐编辑',
        playCount: 1250000,
        songCount: 45,
        description: '精选华语经典与流行歌曲'
      },
      {
        id: 2,
        name: '今天和喜欢的人说话了么',
        cover: 'https://example.com/playlists/love.jpg',
        creator: '情感电台',
        playCount: 980000,
        songCount: 32,
        description: '适合思念时聆听的歌曲'
      },
      {
        id: 3,
        name: '今人心动的宝藏歌曲',
        cover: 'https://example.com/playlists/treasure.jpg',
        creator: '乐迷推荐',
        playCount: 1560000,
        songCount: 50,
        description: '每日更新的精选歌曲'
      }
    ]
  };

  // 排行榜数据
  const rankings = {
    code: 0,
    data: {
      official: [
        {
          id: 1,
          name: '飙升榜',
          cover: 'https://example.com/rankings/rising.jpg',
          updateFrequency: '每天',
          songs: [
            { id: 1, name: '时光流逝', artist: 'Gfriend' },
            { id: 6, name: '你说爱情呀', artist: '刘宇宁' },
            { id: 7, name: '无限', artist: '周深' }
          ]
        },
        {
          id: 2,
          name: '新歌榜',
          cover: 'https://example.com/rankings/new.jpg',
          updateFrequency: '每天',
          songs: [
            { id: 2, name: '玻璃珠', artist: 'Gfriend' },
            { id: 8, name: '爱的存在', artist: '卢卢快闪嘴' },
            { id: 9, name: '烟花易冷 (Live)', artist: '周深' }
          ]
        }
      ],
      custom: [
        {
          id: 3,
          name: '硬地原创音乐榜',
          cover: 'https://example.com/rankings/original.jpg',
          updateFrequency: '每月',
          description: '支持原创音乐人'
        },
        {
          id: 4,
          name: 'Hot音乐榜',
          cover: 'https://example.com/rankings/hot.jpg',
          updateFrequency: '每周',
          description: '流行热歌排行'
        },
        {
          id: 5,
          name: '云音乐民谣榜',
          cover: 'https://example.com/rankings/folk.jpg',
          updateFrequency: '每月',
          description: '精选民谣作品'
        }
      ]
    }
  };

  // 社交动态数据
  const moments = {
    code: 0,
    data: [
      {
        id: 1,
        content: "今天是早上8点，我要发个Mlog好好鼓励下自己，每天都好好学习，好好加油!",
        images: [
          "https://example.com/images/heart_tree.jpg"
        ],
        musicId: null,
        user: {
          id: 2,
          username: "mulan",
          nickname: "木子蘭紫",
          avatar: "https://example.com/avatars/mulan.jpg",
          isVip: true
        },
        likes: 99,
        comments: 500,
        shares: 7,
        createTime: "2023-05-15T08:01:00.000Z"
      },
      {
        id: 2,
        content: "我们就不能互相道个歉，然后回到以前，一起去听一次演唱会么",
        images: [
          "https://example.com/images/girl1.jpg",
          "https://example.com/images/flowers.jpg",
          "https://example.com/images/girls.jpg"
        ],
        musicId: null,
        user: {
          id: 2,
          username: "mulan",
          nickname: "木子蘭紫",
          avatar: "https://example.com/avatars/mulan.jpg",
          isVip: true
        },
        likes: 99,
        comments: 500,
        shares: 7,
        createTime: "2022-12-21T18:30:00.000Z"
      },
      {
        id: 3,
        content: "托时爆肝超然踩点！？算了你们还是听听吧!",
        images: [
          "https://example.com/images/blue_shorts.jpg"
        ],
        musicId: 3,
        user: {
          id: 3,
          username: "happysky",
          nickname: "幸福天空",
          avatar: "https://example.com/avatars/happysky.jpg",
          isVip: false
        },
        likes: 7011,
        comments: 1200,
        shares: 320,
        createTime: "2023-05-14T14:20:00.000Z"
      },
      {
        id: 4,
        content: "我今天看到她了，她剪了头发，眼神好空洞",
        images: [
          "https://example.com/images/gfriend_group.jpg"
        ],
        musicId: null,
        user: {
          id: 4,
          username: "gfriend_official",
          nickname: "Gfriend",
          avatar: "https://example.com/avatars/gfriend.jpg",
          isVip: false
        },
        likes: 123,
        comments: 45,
        shares: 12,
        createTime: "2023-05-13T09:15:00.000Z"
      }
    ]
  };

  // 评论数据
  const comments = {
    code: 0,
    data: [
      {
        id: 1,
        content: "加油，每天都要保持好心情！",
        momentId: 1,
        user: {
          id: 5,
          username: "fan123",
          nickname: "音乐爱好者",
          avatar: "https://example.com/avatars/fan1.jpg"
        },
        createTime: "2023-05-15T08:10:00.000Z"
      },
      {
        id: 2,
        content: "喜欢你的积极态度！",
        momentId: 1,
        user: {
          id: 6,
          username: "melody",
          nickname: "旋律控",
          avatar: "https://example.com/avatars/fan2.jpg"
        },
        createTime: "2023-05-15T08:15:00.000Z"
      },
      {
        id: 3,
        content: "我也想去听演唱会！",
        momentId: 2,
        user: {
          id: 7,
          username: "concertlover",
          nickname: "演唱会爱好者",
          avatar: "https://example.com/avatars/fan3.jpg"
        },
        createTime: "2022-12-21T19:00:00.000Z"
      },
      {
        id: 4,
        content: "什么时候有新歌发布？",
        momentId: 2,
        user: {
          id: 8,
          username: "newmusic",
          nickname: "新歌迷",
          avatar: "https://example.com/avatars/fan4.jpg"
        },
        createTime: "2022-12-21T20:30:00.000Z"
      }
    ]
  };

  // 写入示例数据文件
  fs.writeFileSync(path.join(dataDir, 'songs.json'), JSON.stringify(songs, null, 2));
  fs.writeFileSync(path.join(dataDir, 'artists.json'), JSON.stringify(artists, null, 2));
  fs.writeFileSync(path.join(dataDir, 'playlists.json'), JSON.stringify(playlists, null, 2));
  fs.writeFileSync(path.join(dataDir, 'rankings.json'), JSON.stringify(rankings, null, 2));
  fs.writeFileSync(path.join(dataDir, 'moments.json'), JSON.stringify(moments, null, 2));
  fs.writeFileSync(path.join(dataDir, 'comments.json'), JSON.stringify(comments, null, 2));
  
  console.log('已创建示例数据文件');
} 